package com.item.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;

import com.baidu.yun.channel.auth.ChannelKeyPair;
import com.baidu.yun.channel.client.BaiduChannelClient;
import com.baidu.yun.channel.exception.ChannelClientException;
import com.baidu.yun.channel.exception.ChannelServerException;
import com.baidu.yun.channel.model.PushBroadcastMessageRequest;
import com.baidu.yun.channel.model.PushBroadcastMessageResponse;
import com.baidu.yun.channel.model.PushTagMessageRequest;
import com.baidu.yun.channel.model.PushTagMessageResponse;
import com.baidu.yun.channel.model.PushUnicastMessageRequest;
import com.baidu.yun.channel.model.PushUnicastMessageResponse;
import com.baidu.yun.core.log.YunLogEvent;
import com.baidu.yun.core.log.YunLogHandler;
import com.base.CoreConstants;
import com.base.util.JSONUtils;
import com.base.util.StringUtil;

public class BaiduYunUtil {
	private static final Logger logger = Logger.getLogger(BaiduYunUtil.class);
	
//	public static Integer deployStatus = Integer.parseInt(CoreConstants.getProperty("yun.deployStatus"));
	public static Map<String, BaiduChannelClient> clients = new HashMap<String, BaiduChannelClient>();
	public static Map<String,Integer> deployStatuses = new HashMap<String, Integer>();

	/**
	 * 获得相应学校的推送通道
	 * @param appid
	 * @return
	 */
	public static BaiduChannelClient getAppidClient(String appid) {
		BaiduChannelClient client = clients.get(appid);
		
		if(client == null) {
			String apiKey = CoreConstants.getProperty(appid + ".apiKey");
			String secretKey = CoreConstants.getProperty(appid + ".secretKey");
			if(StringUtils.isNotBlank(apiKey) && StringUtils.isNotBlank(secretKey)){
				ChannelKeyPair pair = new ChannelKeyPair(apiKey, secretKey);
		        // 创建BaiduChannelClient对象实例
				client = new BaiduChannelClient(pair);
		        // 若要了解交互细节，请注册YunLogHandler类
				client.setChannelLogHandler(new YunLogHandler() {
		            public void onHandle(YunLogEvent event) {
		            	logger.debug(event.getMessage());
		            }
		        });
		        clients.put(appid, client); //放入map
		        deployStatuses.put(appid, NumberUtils.toInt(CoreConstants.getProperty(appid+".yun.deployStatus")));
			}
		}
		return client;
	}
	
	/**
	 * 推送单播消息(消息类型为透传，由开发方应用自己来解析消息内容)
	 * @param userid 用户id
	 * @param msg 内容
	 * @return
	 */
	public static int AndroidPushMessage(String userid,Map<String,String> params,String appid){
		try {
			BaiduChannelClient client = getAppidClient(appid);
            // 手机端的ChannelId， 手机端的UserId， 先用1111111111111代替，用户需替换为自己的
            PushUnicastMessageRequest request = new PushUnicastMessageRequest();
            request.setDeviceType(3); // device_type => 1: web 2: pc 3:android 4:ios 5:wp
            //request.setChannelId(11111111111L);
            request.setUserId(userid);
            request.setMessage(JSONUtils.serialize(params));
            // 调用pushMessage接口
            PushUnicastMessageResponse response = client.pushUnicastMessage(request);
            // 返回推送成功数
            return response.getSuccessAmount();
        } catch (ChannelClientException e) {
            // 处理客户端错误异常
            e.printStackTrace();
        } catch (ChannelServerException e) {
            // 处理服务端错误异常
        	//System.out.println(String.format( "request_id: %d, error_code: %d, error_message: %s", e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
        	logger.debug(String.format( "request_id: %d, error_code: %d, error_message: %s", e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
        }
		return 0;
	}
	
	/**
	 * 推送单播通知(Android Push SDK拦截并解析)
	 * @param userid 用户id
	 * @param title 标题
	 * @param msg 内容
	 * @param params 自定义参数
	 * @return 
	 */
	public static int AndroidPushNotification(String userid,String title,String msg,Map<String,String> params, String appid){
		try {
			BaiduChannelClient client = getAppidClient(appid);
            // 手机端的ChannelId， 手机端的UserId， 先用1111111111111代替，用户需替换为自己的
			PushUnicastMessageRequest request = new PushUnicastMessageRequest();
            request.setDeviceType(3); // device_type => 1: web 2: pc 3:android 4:ios 5:wp
            //request.setChannelId(11111111111L);
            request.setUserId(userid);
            request.setMessageType(1);
            
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("title", StringUtil.emptyIfBlank(title));
            map.put("description", StringUtil.emptyIfBlank(msg));
            if(params!=null)
            	map.put("custom_content", params);
            request.setMessage(JSONUtils.serialize(map));
            // 调用pushMessage接口
            PushUnicastMessageResponse response = client.pushUnicastMessage(request);
            // 返回推送成功数
            return response.getSuccessAmount();
        } catch (ChannelClientException e) {
            // 处理客户端错误异常
            e.printStackTrace();
        } catch (ChannelServerException e) {
            // 处理服务端错误异常
//        	//System.out.println(String.format( "request_id: %d, error_code: %d, error_message: %s", e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
        	logger.debug(String.format( "request_id: %d, error_code: %d, error_message: %s", e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
        }
		return 0;
	}
	
	/**
	 * 推送广播消息(消息类型为透传，由开发方应用自己来解析消息内容) 
	 * @param msg 内容
	 * @param params 自定义参数
	 * @return
	 */
	public static int AndroidPushBroadcastMessage(Map<String,String> params,String appid){
		try {
			BaiduChannelClient client = getAppidClient(appid);
            // 创建请求类对象
            PushBroadcastMessageRequest request = new PushBroadcastMessageRequest();
            request.setDeviceType(3); // device_type => 1: web 2: pc 3:android 4:ios 5:wp
            request.setMessage(JSONUtils.serialize(params));
            // 调用pushMessage接口
            PushBroadcastMessageResponse response = client.pushBroadcastMessage(request);
            // 认证推送成功
            return response.getSuccessAmount();
        } catch (ChannelClientException e) {
            // 处理客户端错误异常
            e.printStackTrace();
        } catch (ChannelServerException e) {
            // 处理服务端错误异常
        	logger.debug(String.format("request_id: %d, error_code: %d, error_message: %s",e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
        }
		return 0;
	}
	
	/**
	 * 推送组播消息(消息类型为透传，由开发方应用自己来解析消息内容)
	 * @param tag 组
	 * @param msg 内容
	 * @param params 自定义参数
	 * @return
	 */
	public static int AndroidPushTagMessage(String tag,Map<String,String> params,String appid){
		try {
			BaiduChannelClient client = getAppidClient(appid);
            // 创建请求类对象
			PushTagMessageRequest request = new PushTagMessageRequest();
            request.setDeviceType(3); // device_type => 1: web 2: pc 3:android 4:ios 5:wp
            request.setTagName(tag);
            request.setMessage(JSONUtils.serialize(params));
            // 调用pushMessage接口
            PushTagMessageResponse response = client.pushTagMessage(request);
            // 认证推送成功
            return response.getSuccessAmount();
        } catch (ChannelClientException e) {
            // 处理客户端错误异常
            e.printStackTrace();
        } catch (ChannelServerException e) {
            // 处理服务端错误异常
        	//System.out.println(String.format("request_id: %d, error_code: %d, error_message: %s",e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
        	logger.debug(String.format("request_id: %d, error_code: %d, error_message: %s",e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
        }
		return 0;
	}
	
	/**
	 * 推送组播通知(Android Push SDK拦截并解析)
	 * @param tag 组
	 * @param title 标题
	 * @param msg 内容
	 * @param params 自定义参数
	 * @return
	 */
	public static int AndroidPushTagNotification(String tag,String title,String msg,Map<String,String> params,String appid){
		try {
			BaiduChannelClient client = getAppidClient(appid);
            // 创建请求类对象
			PushTagMessageRequest request = new PushTagMessageRequest();
            request.setDeviceType(3); // device_type => 1: web 2: pc 3:android 4:ios 5:wp
            request.setTagName(tag);
            request.setMessageType(1);
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("title", StringUtil.emptyIfBlank(title));
            map.put("description", StringUtil.emptyIfBlank(msg));
            if(params!=null)
            	map.put("custom_content", params);
            request.setMessage(JSONUtils.serialize(map));
            // 调用pushMessage接口
            PushTagMessageResponse response = client.pushTagMessage(request);
            // 认证推送成功
            return response.getSuccessAmount();
        } catch (ChannelClientException e) {
            // 处理客户端错误异常
            e.printStackTrace();
        } catch (ChannelServerException e) {
            // 处理服务端错误异常
        	logger.debug(String.format("request_id: %d, error_code: %d, error_message: %s",e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
        }
		return 0;
	}
	
	/**
	 * 推送单播通知(IOS APNS)
	 * @param userid 用户id
	 * @param msg 内容
	 * @param params 自定义参数
	 * @return 
	 */
	public static int IosPushNotification(String userid,String msg,int badge,Map<String,String> params,String appid){
		try {
			BaiduChannelClient client = getAppidClient(appid);
            // 手机端的ChannelId， 手机端的UserId， 先用1111111111111代替，用户需替换为自己的
            PushUnicastMessageRequest request = new PushUnicastMessageRequest();
            request.setDeviceType(4); // device_type => 1: web 2: pc 3:android 4:ios 5:wp
            request.setDeployStatus(deployStatuses.get(appid)); // DeployStatus => 1: Developer 2: Production
            //request.setChannelId(11111111111L);
            request.setUserId(userid);
            request.setMessageType(1); 
            Map<String,Object> map = new HashMap<String, Object>();
            if(params!=null){
            	map.putAll(params);
            }
            Map<String,Object> aps = new HashMap<String, Object>();
            aps.put("alert", msg);
            aps.put("badge", badge);
            aps.put("sound", "cat.caf");
            map.put("aps", aps);
            request.setMessage(JSONUtils.serialize(map));
            // 调用pushMessage接口
            PushUnicastMessageResponse response = client.pushUnicastMessage(request);
            // 返回推送成功数
            return response.getSuccessAmount();
        } catch (ChannelClientException e) {
            // 处理客户端错误异常
            e.printStackTrace();
        } catch (ChannelServerException e) {
            // 处理服务端错误异常
        	logger.debug(String.format( "request_id: %d, error_code: %d, error_message: %s", e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
        }
		return 0;
	}
	
	/**
	 * 推送广播消息(IOS APNS)
	 * @param msg 内容
	 * @param params 自定义参数
	 * @return
	 */
	public static int IosPushBroadcastNotification(String msg,Map<String,String> params, String appid){
		try {
			BaiduChannelClient client = getAppidClient(appid);
            // 创建请求类对象
            PushBroadcastMessageRequest request = new PushBroadcastMessageRequest();
            request.setDeviceType(4); // device_type => 1: web 2: pc 3:android 4:ios 5:wp
            request.setMessageType(1);
            request.setDeployStatus(deployStatuses.get(appid)); // DeployStatus => 1: Developer 2: Production
            Map<String,Object> map = new HashMap<String, Object>();
            if(params!=null){
            	map.putAll(params);
            }
            Map<String,Object> aps = new HashMap<String, Object>();
            aps.put("alert", msg);
            aps.put("sound", "cat.caf");
            map.put("aps", aps);
            request.setMessage(JSONUtils.serialize(map));
            // 调用pushMessage接口
            PushBroadcastMessageResponse response = client.pushBroadcastMessage(request);
            // 认证推送成功
            return response.getSuccessAmount();
        } catch (ChannelClientException e) {
            // 处理客户端错误异常
            e.printStackTrace();
        } catch (ChannelServerException e) {
            // 处理服务端错误异常
        	logger.debug(String.format("request_id: %d, error_code: %d, error_message: %s",e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
        }
		return 0;
	}
	
	/**
	 * 推送组播消息(IOS APNS)
	 * @param tag 组
	 * @param msg 内容
	 * @param params 自定义参数
	 * @return
	 */
	public static int IosPushTagNotification(String tag,String msg,Integer badge,Map<String,String> params,String appid){
		try {
			BaiduChannelClient client = getAppidClient(appid);
            // 创建请求类对象
			PushTagMessageRequest request = new PushTagMessageRequest();
            request.setDeviceType(4); // device_type => 1: web 2: pc 3:android 4:ios 5:wp
            request.setTagName(tag);
            request.setDeployStatus(deployStatuses.get(appid)); // DeployStatus => 1: Developer 2: Production
            request.setMessageType(1);
            Map<String,Object> map = new HashMap<String, Object>();
            if(params!=null){
            	map.putAll(params);
            }
            Map<String,Object> aps = new HashMap<String, Object>();
            aps.put("alert", msg);
            aps.put("sound", "cat.caf");
            if(badge != null){
            	aps.put("badge", badge);
            }
            map.put("aps", aps);
            request.setMessage(JSONUtils.serialize(map));
            // 调用pushMessage接口
            PushTagMessageResponse response = client.pushTagMessage(request);
            // 认证推送成功
            return response.getSuccessAmount();
        } catch (ChannelClientException e) {
            // 处理客户端错误异常
            e.printStackTrace();
        } catch (ChannelServerException e) {
            // 处理服务端错误异常
        	//System.out.println("ios" + String.format("request_id: %d, error_code: %d, error_message: %s",e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
        	logger.debug(String.format("request_id: %d, error_code: %d, error_message: %s",e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
        }
		return 0;
	}
}
